package com.easy.deploy.util;

import org.apache.maven.shared.invoker.*;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;

/**
 * @Description mvn执行打包
 * @Date 2023/11/11 14:29
 * @Author 余乐
 **/
public class MavenUtil {


    public static void mvn(String mavenPath, String pomXmlPath, String exec) {
        InvocationRequest request = new DefaultInvocationRequest();
        request.setPomFile(new File(pomXmlPath));
        request.setGoals(Collections.singletonList(exec));
        Invoker invoker = new DefaultInvoker();
        invoker.setMavenHome(new File(mavenPath));
        invoker.setLogger(new PrintStreamLogger(System.err, InvokerLogger.ERROR) {
        });
        invoker.setOutputHandler(System.out::println);
        try {
            invoker.execute(request);
        } catch (MavenInvocationException e) {
            e.printStackTrace();
        }
    }

    public static boolean mvnClean(String mavenPath, String projectRoot) {
        InvocationRequest request = new DefaultInvocationRequest();
        request.setBaseDirectory(new File(projectRoot));
        request.setGoals(Collections.singletonList("clean"));
        Invoker invoker = new DefaultInvoker();
        invoker.setMavenHome(new File(mavenPath));
        //不打印详细的打包过程日志
        invoker.setOutputHandler(null);
        try {
            InvocationResult result = invoker.execute(request);
            if (result.getExitCode() == 0) {
                return true;
            } else {
                return false;
            }
        } catch (MavenInvocationException e) {
            System.out.println("清理旧jar包异常：" + e.getMessage());
            return false;
        }
    }

    public static boolean mvnPackage(String mavenPath, String projectRoot) {
        System.out.println("maven打包中......");
        InvocationRequest request = new DefaultInvocationRequest();
        request.setBaseDirectory(new File(projectRoot));
        request.setGoals(Arrays.asList("clean", "install", "package"));
        Invoker invoker = new DefaultInvoker();
        invoker.setMavenHome(new File(mavenPath));
        //不打印详细的打包过程日志
        invoker.setOutputHandler(null);
        try {
            InvocationResult result = invoker.execute(request);
            if (result.getExitCode() == 0) {
                System.out.println("Build SUCCESS");
                return true;
            } else {
                System.out.println("Build FAILURE");
                return false;
            }
        } catch (MavenInvocationException e) {
            System.out.println("打包异常：" + e.getMessage());
            return false;
        }
    }

}
